package cn.iocoder.an.module.mold.service.upkeeptask;

import cn.iocoder.an.framework.common.enums.UserTypeEnum;
import cn.iocoder.an.framework.security.core.LoginUser;
import cn.iocoder.an.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.an.module.mold.controller.admin.upkeeptask2item.vo.UpkeepTask2itemSaveReqVO;
import cn.iocoder.an.module.mold.dal.dataobject.upkeeptask2item.UpkeepTask2itemDO;
import cn.iocoder.an.module.mold.dal.dataobject.upkeeptobe.UpkeepTobeDO;
import cn.iocoder.an.module.mold.dal.mysql.upkeeptask2item.UpkeepTask2itemMapper;
import cn.iocoder.an.module.mold.dal.mysql.upkeeptobe.UpkeepTobeMapper;
import cn.iocoder.an.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.an.module.system.service.user.AdminUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.*;

import cn.iocoder.an.module.mold.controller.admin.upkeeptask.vo.*;
import cn.iocoder.an.module.mold.dal.dataobject.upkeeptask.UpkeepTaskDO;
import cn.iocoder.an.framework.common.pojo.PageResult;
import cn.iocoder.an.framework.common.util.object.BeanUtils;

import cn.iocoder.an.module.mold.dal.mysql.upkeeptask.UpkeepTaskMapper;

import static cn.iocoder.an.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.an.module.mold.enums.ErrorCodeConstants.*;

/**
 * 模具保养任务 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class UpkeepTaskServiceImpl implements UpkeepTaskService {

    @Resource
    private UpkeepTaskMapper upkeepTaskMapper;

    @Resource
    private UpkeepTobeMapper upkeepTobeMapper;

    @Resource
    private UpkeepTask2itemMapper upkeepTask2itemMapper;

    @Resource
    private AdminUserService userService;

    @Override
    public Long createUpkeepTask(UpkeepTaskSaveReqVO createReqVO) {
        // 插入
        UpkeepTaskDO upkeepTask = BeanUtils.toBean(createReqVO, UpkeepTaskDO.class);
        upkeepTaskMapper.insert(upkeepTask);

        // 返回
        return upkeepTask.getId();
    }

    @Override
    public void updateUpkeepTask(UpkeepTaskSaveReqVO updateReqVO) {
        // 校验存在
        validateUpkeepTaskExists(updateReqVO.getId());
        // 更新
        UpkeepTaskDO updateObj = BeanUtils.toBean(updateReqVO, UpkeepTaskDO.class);
        upkeepTaskMapper.updateById(updateObj);
    }

    @Override
    public void deleteUpkeepTask(Long id) {
        // 校验存在
        validateUpkeepTaskExists(id);
        // 删除
        upkeepTaskMapper.deleteById(id);
    }

    @Override
    public void deleteUpkeepTaskListByIds(List<Long> ids) {
        // 删除
        upkeepTaskMapper.deleteByIds(ids);
    }


    private void validateUpkeepTaskExists(Long id) {
        if (upkeepTaskMapper.selectById(id) == null) {
            throw exception(UPKEEP_TASK_NOT_EXISTS);
        }
    }

    @Override
    public UpkeepTaskDO getUpkeepTask(Long id) {
        return upkeepTaskMapper.selectById(id);
    }

    @Override
    public PageResult<UpkeepTaskDO> getUpkeepTaskPage(UpkeepTaskPageReqVO pageReqVO) {
        //获取当前用户
        if (!SecurityFrameworkUtils.getLoginUser().getUserType().equals(UserTypeEnum.ADMIN.getValue())) {//判断不是管理员
            LoginUser user = SecurityFrameworkUtils.getLoginUser();
            pageReqVO.setAssigneerId(user.getId());
        }

        return upkeepTaskMapper.selectPage(pageReqVO);
    }

    @Override
    public Boolean modStatus(UpkeepTaskModStatusVO modStatusVO) {
        Long id = modStatusVO.getId();
        Integer status = modStatusVO.getStatus();
        String data = modStatusVO.getData();
        LocalDateTime now = LocalDateTime.now();
        UpkeepTaskDO taskDO = upkeepTaskMapper.selectById(id);
        Integer taskStatus = taskDO.getStatus();
        UpkeepTobeDO upkeepTobe = selectUpkeepTobeByTaskId(taskDO.getId());
        switch (status) {
            case 3:
                if (taskStatus != 2 && taskStatus != 4) {
                    throw exception(UPKEEP_TASK_NO_RECEIVED);
                }
                upkeepTobe.setStatus(status);
                upkeepTobeMapper.updateById(upkeepTobe);
                taskDO.setStatus(status);
                if (taskStatus == 2) {
                    taskDO.setTaskReceiveTime(now);
                    taskDO.setTaskStartTime(now);
                }
                upkeepTaskMapper.updateById(taskDO);
                break;
            case 4:
                if (taskStatus != 3 && taskStatus != 5) {
                    throw exception(UPKEEP_TASK_NO_START);
                }
                taskDO.setStatus(status);
                //更新待保养任务中的状态
                upkeepTobe.setStatus(status);
                upkeepTobeMapper.updateById(upkeepTobe);
                taskDO.setJobStartTime(now);
                taskDO.setTaskStartTime(LocalDateTime.now());
                upkeepTaskMapper.updateById(taskDO);
                break;
            case 5:
                if (taskStatus != 3) {
                    throw exception(UPKEEP_TASK_NO_FINISH);
                }
                taskDO.setStatus(status);
                //更新待保养任务中的状态
                upkeepTobe.setStatus(status);
                upkeepTobeMapper.updateById(upkeepTobe);
                upkeepTaskMapper.updateById(taskDO);
                break;
            default:
                throw exception(UPKEEP_TASK_STATUS_ERROR);
        }

        return true;
    }

    public UpkeepTobeDO selectUpkeepTobeByTaskId(Long taskId) {
        return upkeepTobeMapper.selectOne(new LambdaQueryWrapper<UpkeepTobeDO>()
                .eq(UpkeepTobeDO::getTaskId, taskId));
    }

    @Override
    public Boolean workreport(UpkeepTaskWorkReportVO workReportVO) {
        int upkeepStatus = 4;
        UpkeepTaskDO taskDO = upkeepTaskMapper.selectById(workReportVO.getId());
        //更新项目
        List<UpkeepTask2itemSaveReqVO> items = workReportVO.getUpkeepItems();
        //这里需要先删除task2item
        upkeepTask2itemMapper.delete(new LambdaQueryWrapper<UpkeepTask2itemDO>()
                .eq(UpkeepTask2itemDO::getTaskId, taskDO.getId()));
        //循环插入items
        for (UpkeepTask2itemSaveReqVO item : items) {
            upkeepTask2itemMapper.insert(BeanUtils.toBean(item, UpkeepTask2itemDO.class));
        }
        taskDO.setTaskStartTime(workReportVO.getTaskStartTime());
        taskDO.setTaskEndTime(workReportVO.getTaskEndTime());
        taskDO.setTaskExecutionDuration(workReportVO.getTaskExecutionDuration());
        taskDO.setActualStartTime(workReportVO.getTaskStartTime());
        taskDO.setActualEndTime(workReportVO.getTaskEndTime());
        taskDO.setActualExecutionDuration(workReportVO.getTaskExecutionDuration());
        taskDO.setAssigneerIds(workReportVO.getAssigneerIds());
        //这里需要处理名字，将名字拼起来
        if (workReportVO.getAssigneerIds() != null && workReportVO.getAssigneerIds().size() > 0) {
            List<String> names = new ArrayList<>();
            for (Long id : workReportVO.getAssigneerIds()) {
                AdminUserDO user = userService.getUser(id);
                names.add(user.getNickname());
            }
            taskDO.setAssigneerNames(String.join(",", names));
        }

        taskDO.setDescription(workReportVO.getDescription());
        taskDO.setIsCompleted(workReportVO.getIsCompleted());
        taskDO.setStatus(upkeepStatus);
        upkeepTaskMapper.updateById(taskDO);
        UpkeepTobeDO upkeepTobe = selectUpkeepTobeByTaskId(taskDO.getId());
        upkeepTobe.setStatus(upkeepStatus);
        upkeepTobeMapper.updateById(upkeepTobe);
        return true;
    }
}